package org.example.studentmanager.controller;

import org.example.studentmanager.common.utils.R;
import org.example.studentmanager.entity.Course;
import org.example.studentmanager.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private CourseService courseService;

    /**
     * 课程搜索接口，不传入课程名称时查询所有课程
     *
     * @param courseName 课程名称关键字，可选参数
     * @return 符合条件的课程列表
     */
    @GetMapping("/query")
    public R<List<Course>> queryCourses(@RequestParam(value = "courseName", required = false) String courseName) {
        List<Course> courses = courseService.queryCourses(courseName);
        return R.success(courses);
    }

    @GetMapping("/query/{courseId}")
    public R<Course> queryCourseByCourseId(@PathVariable("courseId") Integer courseId) {
        Course course = courseService.queryCourseByCourseId(courseId);
        return R.success(course);
    }

    /**
     *  课程创建接口
     * @param course 课程相关信息
     * @return 创建的课程条数（应该就是0或者1）
     */
    @PostMapping("/insert")
    public R<Integer> insertCourse(@RequestBody Course course) {
        Integer record = courseService.insertCourse(course);
        if (record == 0) {
            return R.error(0, "课程未能创建成功");
        } else {
            return R.success(record);
        }
    }

    @PostMapping("/update")
    public R<Integer> updateCourse(@RequestBody Course course) {
        Integer record = courseService.updateCourse(course);
        if (record == 0) {
            return R.error(0, "课程未能更新成功");
        } else {
            return R.success(record);
        }
    }

    /**
     * 通过 GET 请求删除课程及其关联数据
     *
     * @param courseId 课程 ID
     * @return 操作结果
     */
    @GetMapping("/delete/{courseId}")
    public R<Boolean> deleteCourse(@PathVariable("courseId") Integer courseId) {
        boolean result = courseService.deleteCourse(courseId);
        return R.success(result);
    }
}